var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var YjxBaseModel = require('./YjxBaseModel');
var CONFIG = require('../../config');


var YjxUserPointsHisModel = function (obj) {
    YjxBaseModel.call(this,obj);

  //  `his_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '积分历史id',
  //`user_id` bigint(20) NOT NULL COMMENT '用户id',
  //`cur_pts` bigint(20) NOT NULL DEFAULT '0' COMMENT '当前总积分额',
  //`bal_flg` int(2) NOT NULL DEFAULT '0' COMMENT '收支标记位：0无效，1添加积分，2消耗积分',
  //`bal_pts` bigint(20) NOT NULL DEFAULT '0' COMMENT '收支积分额',
  //`expiry_time` datetime DEFAULT NULL COMMENT '有效截止时间（待定字段）',
  //`state` int(3) unsigned NOT NULL DEFAULT '10' COMMENT '状态:10有效，20冻结，30无效 （待定字段）',
  //`order_id` bigint(20) DEFAULT '0' COMMENT '订单id',
  //`odr_dtl_type` bigint(20) DEFAULT '0' COMMENT '订单明细类型',
  //`odr_dtl_id` bigint(20) DEFAULT '0' COMMENT '订单明细id',
  //`desc` varchar(200) DEFAULT '' COMMENT '备注',
  //`create_time` datetime NOT NULL,
  //`update_time` datetime NOT NULL,
  //`update_by` varchar(50) DEFAULT NULL,
  //`del_flg` int(1) NOT NULL DEFAULT '0',
  //      PRIMARY KEY (`his_id`)
  //  ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COMMENT='用户积分历史表'


};

YjxUserPointsHisModel.prototype = new YjxBaseModel();

// 取得表名
YjxUserPointsHisModel.prototype.getTableName = function(){
    return 'yjx_user_points_his';
};
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
YjxUserPointsHisModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'his_id='+this.his_id;
};

/**
 * 添加用户积分纪录
 * @param userId: 用户id
 * @param balFlg: 收支标记位:1添加积分，2消耗积分
 * @param balPts: 收支积分额
 * @param orderId(可选): 订单id
 * @param odrDtlType(可选): 订单明细类型
 * @param odrDtlId(可选): 订单明细id
 * @param desc(可选): 备注
 * @param callback: 0成功, 1参数错误, 2积分不足, 9其他错误
 */
YjxUserPointsHisModel.prototype.procInsUserPtsHis = function(userId, balFlg, balPts,
                                                             orderId, odrDtlType, odrDtlId, desc,
                                                             callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = 'CALL proc_ins_yjx_pts_his('+ userId +
            ','+balFlg+
            ','+balPts+
            ','+orderId+
            ','+odrDtlType+
            ','+odrDtlId+
            ',"'+desc+'"'+
            ',@result_code'+
            ');';
        /**
         * 注意：
         * userId/balFlg/balPts 必填
         * result_cd: 0成功, 1参数错误, 2积分不足
         */

        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            if(result && result.length>0 && result[0] && result[0].length>0){
                var arrRet = result[0];

                if(arrRet && arrRet.length>0 && arrRet[0]) {
                    return callback(error, arrRet[0].result_code);
                } else {
                    return callback(error, 9);
                }
            }else{
                return callback(error, 9);
            }
        });
    });
};

/**
 * 获取用户秀米信息
 *
 * @author 毛凯
 * @date   2018-3-23
 *
 * @param userId 用户唯一标识
 * @param callback vip信息
 * */
YjxUserPointsHisModel.prototype.getPointsInfo = function (userId,callback) {
    pool.pool.getConnection(function(connectErr, connection) {
        if (connectErr) {
            console.log('YjxMemberModel.getNotifications Err:'+connectErr);
            return callback(connectErr, null);
        }
        var sql ="	SELECT	" +
                "	  yuph.cur_pts AS pointBalance	" +
                "	FROM	" +
                "	  yjx.yjx_user_points_his yuph	" +
                "	WHERE yuph.user_id = "+userId+"	" +
                "	  AND yuph.del_flg = 0	" +
                "	ORDER BY yuph.his_id DESC	" +
                "	LIMIT 1	" ;
            console.log(sql);
        connection.query(sql, function(queryErr, result) {
            // And done with the connection.
            connection.release();
            if(queryErr || result.length <= 0) {
                return callback(queryErr, null);
            }
            return callback(queryErr,result[0]);
        });
    });
};

/*
 * 获取用户秀米明细信息sql
 *
 * @author 毛凯
 * @date   2018-3-23
 *
 * @param userId 用户唯一标识
 * @param callback vip信息
 * */
function getPointsDetail_sql(bForCnt,userId,pageNum,pageSize,types) {
    var sql = '';
    if(bForCnt) {
        sql += ' SELECT COUNT(0) as count ';
    } else {
        sql += "SELECT	" +
            "	  xxx.*,	" +
            "	  p.show_name AS `name`,	" +
            "	  p.`desc` 	AS `desc` " ;
    }
    sql +="	FROM	" +
        "	  (SELECT	" +
        "	    ph.his_id AS id,	" +
        "	    ph.bal_flg AS `type`,	" +
        "	    ph.bal_pts AS points,	" +
        "	    ph.order_id AS orderId,	" +
        "	    DATE_FORMAT(ph.create_time, '%Y-%m-%d %H:%i:%s') AS `time`, " +
        "	    wm.price_id	" +
        "	  FROM	" +
        "	    yjx.yjx_user_points_his ph,	" +
        "	    yjx.yjx_trade_odr_dtl_wm wm	" +
        "	  WHERE ph.odr_dtl_type = 2	" +
        "	    AND ph.bal_flg IN ("+types+")	" +
        "	    AND ph.del_flg = 0	" +
        "	    AND ph.user_id = "+userId+"	" +
        "	    AND wm.del_flg = 0	" +
        "	    AND wm.detail_id = ph.odr_dtl_id	" +
        "	  UNION ALL	" +
        "	  SELECT	" +
        "	    ph.his_id AS id,	" +
        "	    ph.bal_flg AS `type`,	" +
        "	    ph.bal_pts AS points,	" +
        "	    ph.order_id AS orderId,	" +
        "	    DATE_FORMAT(ph.create_time, '%Y-%m-%d %H:%i:%s') AS `time`, " +
        "	    tv.price_id	" +
        "	  FROM	" +
        "	    yjx.yjx_user_points_his ph,	" +
        "	    yjx.yjx_trade_odr_dtl_vip tv	" +
        "	  WHERE ph.odr_dtl_type = 8	" +
        "	    AND ph.del_flg = 0	" +
        "	    AND ph.bal_flg IN ("+types+")	" +
        "	    AND ph.user_id = "+userId+"	" +
        "	    AND tv.del_flg = 0	" +
        "	    AND tv.detail_id = ph.odr_dtl_id	" +
        "	  UNION ALL	" +
        "	  SELECT	" +
        "	    ph.his_id AS id,	" +
        "	    ph.bal_flg AS `type`,	" +
        "	    ph.bal_pts AS points,	" +
        "	    ph.order_id AS orderId,	" +
        "	    DATE_FORMAT(ph.create_time, '%Y-%m-%d %H:%i:%s') AS `time`, " +
        "	    tp.price_id	" +
        "	  FROM	" +
        "	    yjx.yjx_user_points_his ph,	" +
        "	    yjx.yjx_trade_odr_dtl_pts tp	" +
        "	  WHERE ph.odr_dtl_type = 16	" +
        "	    AND ph.del_flg = 0	" +
        "	    AND ph.bal_flg IN ("+types+")	" +
        "	    AND ph.user_id = "+userId+"	" +
        "	    AND tp.del_flg = 0	" +
        "	    AND tp.detail_id = ph.odr_dtl_id) xxx,	" +
        "	  yjx.yjx_price p	" +
        "	WHERE p.del_flg = 0	" +
        "	  AND p.price_id = xxx.price_id	" +
        "	ORDER BY xxx.time DESC	" ;
    if(!bForCnt){
        if (typeof pageNum !== 'undefined' && pageNum !== null &&
            typeof pageSize !== 'undefined' && pageSize !== null)
        {
            var skipCnt = Number(pageNum||'0') * Number(pageSize||'0');
            sql += " LIMIT " + skipCnt + "," + Number(pageSize||'0');
        }
    }
    return sql;
}
/**
 * 获取用户秀米明细列表
 *
 * @author 毛凯
 * @date 2018-3-24
 *
 * @param userId 用户标识
 * @param pageNum 页码
 * @param pageSize 页容量
 * @param callback 回调
 *           err: 查询失败
 *           results: 用户对应收藏列表
 *
 * */
YjxUserPointsHisModel.prototype.getUserPointsDetailList = function (userId,pageNum,pageSize,types,callback){
    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxFavoriteModel.js [getUserFavList] getConErr' + getConErr);
            return callback(getConErr, null);
        }
        var sql = getPointsDetail_sql(false,userId,pageNum,pageSize,types);
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxFavoriteModel.js [getUserFavList] queryErr' + queryErr)
            }
            return callback(queryErr, results);
        });
    })
};

/**
 * 获取用户秀米明细数量
 *
 * @author 毛凯
 * @date 2018-3-24
 *
 * @param userId 用户标识
 * @param pageNum 页码
 * @param pageSize 页容量
 * @param types 增加或者减少积分 1增加  2 减少
 * @param callback 回调
 *           err: 查询失败
 *           count: 用户收藏列表数量
 *
 * */
YjxUserPointsHisModel.prototype.getUserPointsDetailCnt = function (userId,pageNum,pageSize,types,callback){
    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxFavoriteModel.js [getUserFavListCnt] getConErr' + getConErr);
            return callback(getConErr, null);
        }
        var sql = getPointsDetail_sql(true,userId,pageNum,pageSize,types);
        console.log(sql);

        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxFavoriteModel.js [getUserFavListCnt] queryErr' + queryErr)
                return callback(queryErr, null);
            }
            if (results && results[0]) {
                return callback(queryErr, results[0].count);
            }
            return callback(queryErr,null);
        });
    })
};





module.exports = YjxUserPointsHisModel;

